﻿using Microsoft.AspNet.Identity;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.UI;
using System.Xml.Linq;
using YaYun.Models;
//using Microsoft.Owin;


namespace YaYun.Controllers
{
    public class HomeController : Controller
    {
        public void SessionValue()
        {
            string employeeName = Session["EmployeeName"] as string;
            string touxiang = Session["touxiang"] as string;
            if (employeeName != null)
            {
                ViewBag.EmployeeName = employeeName;

            }
            if (touxiang != null)
            {
                ViewBag.touxiang = touxiang;
            }
        }
        public ActionResult Index()
        {
            SessionValue();
            return View();
        }
        public ActionResult index2()
        {
            SessionValue();
            return View();
        }

        public ActionResult Login(string name, int page = 1)
        {
            int pageSize = 12; // 每页显示的记录数
            using (var db = new YayunEntities3())
            {
                SessionValue();
                var query = db.Employee.Include("Position1").Include("Salary").Include("Department1").OrderBy(n => n.id).AsQueryable();
                if (!string.IsNullOrEmpty(name))
                {
                    query = query.Where(n => n.EmployeeName.Contains(name));
                }
                var totalCount = query.Count(); // 获取数据总记录数
                var totalPages = (int)Math.Ceiling((double)totalCount / pageSize); // 计算总页数
                if (page < 1) // 如果页数小于1
                {
                    page = 1; // 将页数设置为第一页
                }
                else if (page > totalPages) // 如果页数超出总页数
                {
                    page = totalPages; // 将页数设置为最后一页
                }
                var employees = query.Skip((page - 1) * pageSize)
                                     .Take(pageSize).OrderBy(m => m.enter_date)
                                     .ToList();
                ViewBag.CurrentPage = page;
                ViewBag.TotalPages = totalPages;
                ViewBag.SearchName = name;
                return View(employees); // 返回局部视图
            }
          
        }
        [HttpPost]
        public ActionResult Login(Emp_User u)
        {
            if (ModelState.IsValid)
            {
                using (var db=new YayunEntities3())
                {
                    var user = db.Emp_User.FirstOrDefault(n=>n.Emp_Email ==u.Emp_Email);
                    if (user==null)
                    {
                        ModelState.AddModelError("1", "邮箱或者密码不正确");
                    }
                    else
                    {
                        return RedirectToAction("/index");
                    }
                }
            }
            return View();
        }      

        /// <summary>
        /// 员工
        /// </summary>
        /// <returns></returns>
        public ActionResult Employee(string name,int page=1)
        {
            int pageSize = 10; // 每页显示的记录数
            using (var db = new YayunEntities3())
            {
                SessionValue();
                var query = db.Employee.Include("Position1").Include("Salary").Include("Department1").OrderBy(n => n.id).AsQueryable();
                if (!string.IsNullOrEmpty(name))
                {
                    query = query.Where(n => n.EmployeeName.Contains(name));
                }
                var totalCount = query.Count(); // 获取数据总记录数
                var totalPages = (int)Math.Ceiling((double)totalCount / pageSize); // 计算总页数
                if (page < 1) // 如果页数小于1
                {
                    page = 1; // 将页数设置为第一页
                }
                else if (page > totalPages) // 如果页数超出总页数
                {
                    page = totalPages; // 将页数设置为最后一页
                }
                var employees = query.Skip((page - 1) * pageSize)
                                     .Take(pageSize).OrderBy(m=>m.enter_date)
                                     .ToList();
                ViewBag.CurrentPage = page;
                ViewBag.TotalPages = totalPages;
                ViewBag.SearchName = name;
                return View(employees); // 返回局部视图
            }
           
        }

        public ActionResult EmpDel(int id, int state)
        {
            SessionValue();
            using (var db = new YayunEntities3())
            {
                var de = db.Employee.FirstOrDefault(n => n.id == id);
                if (de.state ==0 )
                {
                    de.state = 1;
                  
                }
                else
                {
                    de.state = 0;

                }
                db.SaveChanges();
                return RedirectToAction("Employee");
            } 
           
        }

        public ActionResult ADDEmployee( )
        {
            SessionValue();
            using (var db=new YayunEntities3())
            {
                var deps = db.Department.ToList();
                ViewBag.id = new SelectList(deps, "id", "DepartmentName");
                var dep = db.Position.ToList();
                ViewBag.id1 = new SelectList(dep, "id", "PositionName");
            }
            return View();
        }
        [HttpPost]
        public ActionResult ADDEmployee(Employee emp )
        {
            SessionValue();
            using (var db = new YayunEntities3())
            {
                var deps = db.Department.ToList();
                ViewBag.DEP_id = new SelectList(deps, "DEP_id", "DepartmentName");

                var dep = db.Position.ToList();
                ViewBag.posi_id = new SelectList(dep, "posi_id", "PositionName");

                db.Employee.Add(emp);    
                int num = db.SaveChanges();
                if (num > 0)
                {                    
                    return Content("<script>alert('添加成功！');window.location='/home/Employee'</script>");
                }
            }
            return View();
        }      

        public ActionResult edit(int id)
        {
            SessionValue();
            using (var db = new YayunEntities3())
            {
                var de = db.Employee.Include("Position1").Include("Department1").FirstOrDefault(n => n.id == id);
                return View(de);
            }

        }
        public ActionResult UpdateEmployee( )
        {
            SessionValue();
            return View();
        }
        [HttpPost]
        public ActionResult UpdateEmployee(Employee employee)
        {
            SessionValue();
            if (ModelState.IsValid)
            {
                using (var db = new YayunEntities3())
                {
                    var existingEmployee = db.Employee.FirstOrDefault(n=>n.id==employee.id);
                    if (existingEmployee != null)
                    {
                        existingEmployee.EmployeeName = employee.EmployeeName;
                        existingEmployee.phone = employee.phone;
                        existingEmployee.email = employee.email;
                        existingEmployee.gender = employee.gender;
                        existingEmployee.Position1 = employee.Position1;
                        existingEmployee.Department1 = employee.Department1;

                        db.SaveChanges();
                    }
                }

                return RedirectToAction("Employee");
            }
            else
            {
                return View(employee);
            }
        }
        /// <summary>
        /// 匹配ID数字替换字符串方法
        /// </summary>
        /// <param name="departmentId"></param>
        /// <returns></returns>
        public string GetDepartmentName(int departmentId)
        {
            switch (departmentId)
            {
                case 1:
                    return "技术部";
                case 2:
                    return "人事部";
                case 3:
                    return "销售部";
                case 4:
                    return "财务部";
                default:
                    return "";
            }
        }

        /// <summary>
        /// 部门
        /// </summary>
        /// <returns></returns>
        public ActionResult Department()
        {
         
            using (var db = new YayunEntities3())
            {
                SessionValue();
                //Include 包括,同时查出所在的部门
                var emps = db.Department.Include("Employee").Include("Leader1").ToList();
                return View(emps);
            }
          
        }

        /// <summary>
        /// 职位表
        /// </summary>
        /// <returns></returns>
        public ActionResult Position(int page = 1)
        {
            SessionValue();
            int pageSize = 10; // 每页显示的记录数
            using (var db = new YayunEntities3())
            {
                var totalCount = db.Position.Count(); // 获取数据总记录数
                var totalPages = (int)Math.Ceiling((double)totalCount / pageSize); // 计算总页数
                if (page < 1) // 如果页数小于1
                {
                    page = 1; // 将页数设置为第一页
                }
                else if (page > totalPages) // 如果页数超出总页数
                {
                    page = totalPages; // 将页数设置为最后一页
                }
                var notices = db.Position.Include("Employee").Include("Department").OrderBy(n => n.posi_id)
                                          .Skip((page - 1) * pageSize)
                                          .Take(pageSize)
                                          .ToList();
                ViewBag.CurrentPage = page;
                ViewBag.pageSize = pageSize;
                ViewBag.TotalPages = totalPages;
                return View(notices);
            }
        }
        /// <summary>
        /// 员工薪资表
        /// </summary>
        /// <returns></returns>
        public ActionResult Salary(string name, int page = 1)
        {
            SessionValue();
            int pageSize = 10; // 每页显示的记录数
            using (var db = new YayunEntities3())
            {
                var totalCount = db.Salary.Count(); // 获取数据总记录数
                var query = db.Salary.Include("Employee").AsQueryable(); // 修改此行，将查询对象更改为Salary表，并包含Employee表的关联数据
                if (!string.IsNullOrEmpty(name))
                {
                    query = query.Where(s => s.Employee.EmployeeName.Contains(name)); // 修改此行，将查询条件更改为Employee表的EmployeeName字段
                }
                var totalPages = (int)Math.Ceiling((double)totalCount / pageSize); // 计算总页数
                if (page < 1) // 如果页数小于1
                {
                    page = 1; // 将页数设置为第一页
                }
                else if (page > totalPages) // 如果页数超出总页数
                {
                    page = totalPages; // 将页数设置为最后一页
                }

                var notices = query.Take(pageSize).OrderBy(n => n.id).ToList();
                ViewBag.CurrentPage = page;
                ViewBag.TotalPages = totalPages;
                ViewBag.SearchName = name;
                return View(notices);
            }
        }
        public ActionResult ADDSalary(string name)
        {
            SessionValue();
            using (var db = new YayunEntities3())
            {
                var de = db.Employee.Where(n => n.EmployeeName.Contains(name)).ToList();
                ViewBag.SearchName = name;
                return View(de);
            }
        }
        [HttpPost]
        public ActionResult ADDSalary(Salary salary)
        {         
            using (var db = new YayunEntities3())
            {
                db.Salary.Add(salary);
                int num = db.SaveChanges();
                if (num > 0)
                {
                    return Content("<script>alert('添加成功！');window.location='/home/Salary'</script>");
                }
                else
                {
                    return Content("<script>alert('添加失败！');window.location='/home/ADDSalary'</script>");
                }
            }
           
        }
        public ActionResult AllEmployeeADDsalary(string name, int page = 1)
        {
            SessionValue();
            int pageSize = 10; // 每页显示的记录数
            using (var db = new YayunEntities3())
            {
                var query = db.Employee.Include("Position1").Where(n => n.state == 0).OrderBy(n => n.id).AsQueryable();
                if (!string.IsNullOrEmpty(name))
                {
                    query = query.Where(n => n.EmployeeName.Contains(name));
                }
                var totalCount = query.Count(); // 获取数据总记录数
                var totalPages = (int)Math.Ceiling((double)totalCount / pageSize); // 计算总页数
                if (page < 1) // 如果页数小于1
                {
                    page = 1; // 将页数设置为第一页
                }
                else if (page > totalPages) // 如果页数超出总页数
                {
                    page = totalPages; // 将页数设置为最后一页
                }
                var employees = query.Skip((page - 1) * pageSize)
                                     .Take(pageSize).OrderBy(m => m.state)
                                     .ToList();
                ViewBag.CurrentPage = page;
                ViewBag.TotalPages = totalPages;
                ViewBag.SearchName = name;
                return View(employees); // 返回局部视图
            }

        }

        public ActionResult editemp(int id)
        {
            SessionValue();
            using (var db = new YayunEntities3())
            {
                var de = db.Employee.Include("Position1").Include("Department1").FirstOrDefault(n => n.id == id);
                return View(de);
            }
        }
        /// <summary>
        /// 离职记录表
        /// </summary>
        /// <returns></returns>

        public ActionResult Leave_Record(string name, int page = 1)
        {
            SessionValue();
            int pageSize = 10; // 每页显示的记录数
            using (var db = new YayunEntities3())
            {
                var query = db.Employee.Include("Position1").Where(n => n.state == 1).OrderBy(n => n.id).AsQueryable();
                if (!string.IsNullOrEmpty(name))
                {
                    query = query.Where(n => n.EmployeeName.Contains(name));
                }
                var totalCount = query.Count(); // 获取数据总记录数
                var totalPages = (int)Math.Ceiling((double)totalCount / pageSize); // 计算总页数
                if (page < 1) // 如果页数小于1
                {
                    page = 1; // 将页数设置为第一页
                }
                else if (page > totalPages) // 如果页数超出总页数
                {
                    page = totalPages; // 将页数设置为最后一页
                }
                var employees = query.Skip((page - 1) * pageSize)
                                     .Take(pageSize).OrderBy(m => m.state)
                                     .ToList();
                ViewBag.CurrentPage = page;
                ViewBag.TotalPages = totalPages;
                ViewBag.SearchName = name;
                return View(employees); // 返回局部视图
            }
        }
        public ActionResult resume(int id, int state)
        {
            SessionValue();

            using (var db = new YayunEntities3())
            {
                var de = db.Employee.Include("Position1").FirstOrDefault(n => n.id == id);
                if (de != null)
                {
                    de.state = 0;
                    db.SaveChanges();
                }
            }
            return RedirectToAction("Leave_Record");
        }
        /// <summary>
        /// 公告表
        /// </summary>
        /// <returns></returns>
        public ActionResult notice(int page = 1)
        {
            SessionValue();
            int pageSize = 10; // 每页显示的记录数
            if (page < 1)
            {
                page = 1;
            }
            using (var db = new YayunEntities3())
            {
                var notices = db.notice.OrderBy(n => n.publish_time);
                var pagedNotices = notices.Skip((page - 1) * pageSize).Take(pageSize).ToList();
                var totalItems = notices.Count();
                var totalPages = (int)Math.Ceiling((double)totalItems / pageSize);
                ViewBag.CurrentPage = page;
                ViewBag.TotalPages = totalPages;
                return View(pagedNotices);
            }
        }

        public ActionResult DELnotice(int id)
        {
            SessionValue();
       
            using (var db = new YayunEntities3())
            {
                var notices = db.notice.FirstOrDefault(n=>n.id==id);
                db.notice.Remove(notices);
                if (db.SaveChanges()>0)
                {
                    return Content("<script>alert('删除成功！');window.location='/home/notice'</script>");
                }

                else
                {
                    return Content("<script>alert('删除失败！');window.location='/home/notice'</script>");
                }              
            }
        }
        public ActionResult ADDnotice()
        {
            return View();
        }
        [HttpPost]
        public ActionResult ADDnotice(notice n)
        {
                using (var db = new YayunEntities3())
                {
                    db.notice.Add(n);
                    int num = db.SaveChanges();
                    if (num > 0)
                    {
                        return Content("<script>alert('添加成功！');window.location='/home/notice'</script>");
                    }
                    else
                    {
                        return Content("<script>alert('添加失败！');window.location='/home/notice'</script>");
                    }
                }
            
        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        /// 

        /// <summary>
        /// 考勤表
        /// </summary>
        /// <returns></returns>       
        public ActionResult attendance_records(int page=1)
        {
            SessionValue();
            int pageSize = 10; // 每页显示的记录数
            using (var db = new YayunEntities3())
            {
                var totalCount = db.attendance_records.Count(); // 获取数据总记录数
                var totalPages = (int)Math.Ceiling((double)totalCount / pageSize); // 计算总页数
                if (page < 1) // 如果页数小于1
                {
                    page = 1; // 将页数设置为第一页
                }
                else if (page > totalPages) // 如果页数超出总页数
                {
                    page = totalPages; // 将页数设置为最后一页
                }
                var notices = db.attendance_records.Include("Employee").OrderByDescending(n => n.check_in)
                                          .Skip((page - 1) * pageSize)
                                          .Take(pageSize)
                                          .ToList();
                ViewBag.CurrentPage = page;
                ViewBag.pageSize = pageSize;
                ViewBag.TotalPages = totalPages;
                return View(notices);
            }
        }
        public ActionResult ADDattendance_records(  )
        {
            SessionValue();
            using (var db = new YayunEntities3())
            {
                var deps = db.Department.ToList();
                ViewBag.DepartmentId = new SelectList(deps, "id", "DepartmentName");
                ViewBag.PositionName = new SelectList(deps, "id", "PositionName");

                
            }
           
            return View();
        }
        [HttpPost]
        public ActionResult ADDattendance_records(attendance_records add)
        {
            SessionValue();
            using (var db = new YayunEntities3())
            {
                var deps = db.Department.ToList();
                ViewBag.DepartmentId = new SelectList(deps, "id", "DepartmentName");
                ViewBag.PositionName = new SelectList(deps, "id", "PositionName");

                

                db.attendance_records.Add(add);
                int numede= db.SaveChanges();
                if (numede>0)
                {
                    return JavaScript("alert('添加成功');");
                }

                else
                {
                    return JavaScript("alert('添加失败');");
                }
            }
         
        }
        /// <summary>
        /// 项目业务表
        /// </summary>
        /// <returns></returns>       
        public ActionResult project_business(int page=1)
        {
            SessionValue();
            int pageSize = 10; // 每页显示的记录数
            using (var db = new YayunEntities3())
            {
                var totalCount = db.project_business.Count(); // 获取数据总记录数
                var totalPages = (int)Math.Ceiling((double)totalCount / pageSize); // 计算总页数
                if (page < 1) // 如果页数小于1
                {
                    page = 1; // 将页数设置为第一页
                }
                else if (page > totalPages) // 如果页数超出总页数
                {
                    page = totalPages; // 将页数设置为最后一页
                }
                var notices = db.project_business.Include("Department").OrderBy(n => n.id)
                                          .Skip((page - 1) * pageSize)
                                          .Take(pageSize)
                                          .ToList();
                ViewBag.CurrentPage = page;
                ViewBag.pageSize = pageSize;
                ViewBag.TotalPages = totalPages;
                return View(notices);
            }

        }
        /// <summary>
        /// 员工请假表
        /// </summary>
        /// <returns></returns>
       
        public ActionResult employee_leave(int page = 1)
        {
            SessionValue();
            int pageSize = 10; // 每页显示的记录数
            using (var db = new YayunEntities3())
            {
                var totalCount = db.employee_leave.Count(); // 获取数据总记录数
                var totalPages = (int)Math.Ceiling((double)totalCount / pageSize); // 计算总页数
                if (page < 1) // 如果页数小于1
                {
                    page = 1; // 将页数设置为第一页
                }
                else if (page > totalPages) // 如果页数超出总页数
                {
                    page = totalPages; // 将页数设置为最后一页
                }
                var notices = db.employee_leave.Include("Employee").OrderBy(n => n.id)
                                          .Skip((page - 1) * pageSize)
                                          .Take(pageSize)
                                          .ToList();
                ViewBag.CurrentPage = page;
                ViewBag.pageSize = pageSize;
                ViewBag.TotalPages = totalPages;
                return View(notices);
            }
        }
        public ActionResult admin()
        {
            SessionValue();
            using (var db = new YayunEntities3())
            {
                //Include 包括,同时查出所在的部门
                var emps = db.admin.ToList();
                return View(emps);
            }

        }

        /// <summary>
        /// 退出登录后消除用户
        /// </summary>
        /// <returns></returns>


        public ActionResult testView()
        {
            return View();
        }
    }
}